package cpt202.project.controller;

import cpt202.project.entity.Record;
import cpt202.project.service.BookService;
import cpt202.project.service.exception.DeleteException;
import cpt202.project.service.exception.InsertException;
import cpt202.project.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/books")
public class AccountbookController {
    @Autowired
    private BookService Book; //注入业务层 BookService,命名为Book

    @RequestMapping("/add_new_book")
    public JsonResult<Integer> addNewBook(String bookname,HttpServletRequest request){
        JsonResult<Integer> result = new JsonResult<>();
        Object email = request.getSession().getAttribute("email"); //从session中获取用户的email
        try{
            Integer newbookID = Book.add((String) email, bookname);
            result.setState(200); //200代表用户成功创建新的账本
            result.setMessage("创建成功");
            result.setData(newbookID);
        }
        catch (InsertException e) {
            result.setState(3000); //3000表示新建项目时发生错误
            result.setMessage("创建账本时发生未知错误");
        }
        return result;
    }

    @RequestMapping("/delete_book")
    public JsonResult<Void> deleteBook(Integer bookId){
        JsonResult<Void> result = new JsonResult<>();
        try{
            Book.delete(bookId);
            result.setState(200); //200代表用户成功删除账本
            result.setMessage("删除成功");
        }
        catch (DeleteException e) {
            result.setState(3020); //3020表示删除项目时发生错误
            result.setMessage("删除账本时发生未知错误");
        }
        return result;
    }

    @RequestMapping("/switch_book")
    public JsonResult<Record []> switchBook(Integer bookId) {
        JsonResult<Record []> result = new JsonResult<>();
        Record[] records= Book.switchBook(bookId);
        result.setData(records);
        result.setState(200); //200代表用户成功切换目标账本
        return result;
    }
}
